import { Inject, Provide, Scope, ScopeEnum } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { TaskRecordEntity } from '../entity/record';
import { BaseSysParamService } from '../../base/service/sys/param';
import * as moment from 'moment';

/**
 * 任务记录
 */
@Scope(ScopeEnum.Request, { allowDowngrade: true })
@Provide()
export class TaskRecordService extends BaseService {
  @InjectEntityModel(TaskRecordEntity)
  taskRecordEntity: Repository<TaskRecordEntity>;

  @Inject()
  baseSysParamService: BaseSysParamService;

  /**
   * 保存
   * @param record
   */
  async save(record: any) {
    // 一个任务最多保留记录数
    const recordCount = await this.baseSysParamService.dataByKey('recordCount');
    const count = await this.taskRecordEntity.countBy({
      jobId: record.jobId,
      appId: record.appId,
    });
    if (count >= recordCount) {
      // 删除最早的一条记录
      const info = await this.taskRecordEntity
        .createQueryBuilder()
        .where('jobId = :jobId and appId = :appId', {
          jobId: record.jobId,
          appId: record.appId,
        })
        .orderBy('id', 'ASC')
        .getOne();
      await this.taskRecordEntity.delete(info.id);
    }
    await this.taskRecordEntity.save(record);
    return record.id;
  }

  /**
   * 超时任务
   */
  async overtimeStatus() {
    // 超时时间：单位分钟
    const overtimeConfig = await this.baseSysParamService.dataByKey('overtime');
    // 筛选出超时的任务
    await this.taskRecordEntity
      .createQueryBuilder()
      .update()
      .where('status = :status', { status: 0 })
      .andWhere('createTime < :createTime', {
        createTime: moment().subtract(overtimeConfig, 'minutes').toDate(),
      })
      .set({
        status: 2,
        result: '任务超时',
        resultTime: new Date(),
      })
      .execute();
  }
}
